package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 新增菜品
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result addDish(DishDTO dto) {
        //1.非空判断
        if(dto.getCategoryId()==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.新增菜品表，一条数据，当事务没有提交之前，我们必须返回菜品id，供新增口味使用
        Dish dish=new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.insertDish(dish);

        //3.新增口味集合，多条数据，执行批量新增，一定要拿到菜品id
        List<DishFlavor> flavors = dto.getFlavors();

        if(flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.insertDishFlavorList(flavors);
        }

        //清理缓存
        String pattern="dish_"+dish.getCategoryId();
        cleanCache(pattern);

        //4.返回数据
        return Result.success();
    }

    /**
     * 查询菜品管理
     * @param dto
     * @return
     */
    @Override
    public Result pageDish(DishPageQueryDTO dto) {
        //1.非空判断
        if(dto.getPage()==null){
            dto.setPage(1);
        }
        if(dto.getPageSize()==null){
            dto.setPageSize(5);
        }
        //2.执行分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        //3.条件查询
        Page<Dish> page = dishMapper.pageDish(dto);
        //3.1 总条数以及菜品集合
        long total = page.getTotal();
        List<Dish> dishList = page.getResult();

        //3.3声明一个list用来承载vo对象集合
        List<DishVO>dishVoList=new ArrayList(dishList.size());

        //3.2 为每一条数据添加菜品分类名称
        dishList.forEach(dish -> {
            //1.声明一个vo对象
            DishVO vo=new DishVO();
            BeanUtils.copyProperties(dish,vo);
            //2.获取分类名称
            Category category = categoryMapper.getById(vo.getCategoryId());
            vo.setCategoryName(category.getName());
            //3.写入数据到voList
            dishVoList.add(vo);
        });


        //4.返回数据
        PageResult pageResult=new PageResult();
        pageResult.setRecords(dishVoList);
        pageResult.setTotal(total);
        return Result.success(pageResult);
    }

    /**
     * 删除菜品以及批量删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result deleteDish(List<Long> ids) {
        //1.非空判断
        if(ids==null || ids.size()==0){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.查询当前菜品是否存在
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            //3.如果存在，判断状态如果是起售状态，则不能删除
            if(dish!=null){
                if(dish.getStatus()== StatusConstant.ENABLE){
                    return Result.error(MessageConstant.DISH_ON_SALE);
                }
            }
        }

        //4.如果存在，被套餐关联的话也不能删除
        List<Long> setmealDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealDishIds!=null && setmealDishIds.size()>0){
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //5.如果存在，删除菜品之后，口味数据也删除
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);

        //6.清理redis中的缓存
        //清理缓存
        String pattern="dish_*";
        cleanCache(pattern);

        //6.返回数据
        return Result.success();
    }

    /**
     * 单一查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public Result<DishVO> getById(Long id) {
        //1.非空判断
        if(id==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.根据id查询当前数据
            //2.1 查询菜品
        Dish dish = dishMapper.getById(id);
            //2.2查询口味
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getDishFalvorListById(id);

        //2.3 口味关联到菜品中
        DishVO vo=new DishVO();
        BeanUtils.copyProperties(dish,vo);
        vo.setFlavors(dishFlavorList);

        //3.如果存在，则返回数据
        return Result.success(vo);
    }

    /**
     * 修改菜品
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result updateDish(DishDTO dto) {
        //1.非空判断
        if(dto.getId()==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.根据id修改dish表
        Dish dish=new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.updateDishById(dish);

        //3.根据菜品id去删除口味表数据集合
        dishFlavorMapper.deleteDishFlavor(Arrays.asList(dto.getId()));


        //4.插入新的口味数据到口味表中
        List<DishFlavor> flavors = dto.getFlavors();//每个DishFlavor只包含了name和value,并不包含dish_id
        if(flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.insertDishFlavorList(flavors);
        }

        //清理缓存
        String pattern="dish_"+dish.getCategoryId();
        cleanCache(pattern);

        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        String key="dish_"+dish.getCategoryId();
        //首先去查询redis,如果redis中有数据，则直接返回
        String dishVoListStr = redisTemplate.opsForValue().get(key);
        //把字符串转成list集合
        List<DishVO> dishVOListForRedis = JSONArray.parseArray(dishVoListStr, DishVO.class);
        if(dishVOListForRedis!=null && dishVOListForRedis.size()>0){
            return dishVOListForRedis;
        }
        //否则，没有数据，查询mysql，写入数据到redis中
        //条件查询对应的菜品集合
        List<Dish> dishList = dishMapper.list(dish);
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getDishFalvorListById(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        //写入数据到redis
        redisTemplate.opsForValue().set(key,JSON.toJSONString(dishVOList));

        return dishVOList;
    }

    /**
     * 封装的一个清理缓存的方法
     * @param pattern  表达式
     */
    private void cleanCache(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
